<?php

namespace admin\controllers;

use common\models\UserBond;
use Yii;
use common\helpers\Pager;
use common\helpers\Checker;
use common\models\User;
use common\models\UserUpload;

class UserController extends Controller {
    
    // 设置所属一级导航 不设置表示 就是当前类名
    public $parent = 'member';

    /**
     * showing designer list
     * @return string
     */
    public function actionUserDesigner()
    {
        return $this->render('user-designer');
    }

    /**
     * showing employer list
     * @return string
     */
    public function actionUserEmployer()
    {
        return $this->render('user-employer');
    }

    /**
     * show user data
     */
    public function actionUserList()
    {
        $params = $this->request->post();
        $rules = [
            'param' => [
                'username' => ['账号', ['username']],
                'user_id' => ['用户编号', ['int']],
                'role' => ['账号类型', ['inkey' => User::$roleSelector, 'required']],
                'start' => ['开始时间', ['date' => 'Y-m-d']],
                'end' => ['结束时间', ['date' => 'Y-m-d']],
                'mobile' => ['手机号', ['mobile']],
                'email' => ['邮箱', ['email']],
                'status' => ['状态', ['inkey' => User::$statusSelector]],
            ],
        ];
        $checker = Checker::authentication($rules, $params);
        if($checker['code'] != SuccessCode) {
            return $this->json('Param.Error', $checker['message']);
        }
        foreach(['start', 'end'] as $key) {
            if(empty($params[$key])) {
                continue;
            }
            $params[$key] = strtotime($params[$key]);
        }
        $params['deleted_at'] = '0';
        $query = User::filterConditions(User::initCondition(['username', 'role', 'mobile', ['created_at', '>=', 'start'], ['created_at', '<', 'end'], 'email', 'status', 'deleted_at'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * showing User list
     * @return string
     */
    public function actionUserPending()
    {
        if( ! $this->isJson) {
            return $this->render('user-pending');
        }
        $param = $this->request->post();
        $param['role'] = User::RoleDesigner;
        $param['status'] = User::StatusPending;
        $query = User::filterConditions(User::initCondition(['username', 'role', 'mobile', 'email'], $param));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * show user information
     * @param id int by get request
     * @return string
     */
    public function actionDesignerDetail()
    {
        $rule = [
            'param' => [
                'username' => ['账号', ['username', 'required']],
                'password_digest' => ['密码', ['password', 'required' => true]],
                'mobile' => ['手机号', ['mobile', 'required']],
                'nickname' => ['昵称', ['maxlength' => 16, 'required']],
            ],
        ];
        $user = null;
        $userId = $this->request->get('id');
        if($userId && ( ! $user = User::canEdit($userId))) {
            return $this->error('无效的用户（Invalid User）', 'user/user-designer');
        }
        if($user && $user->employer()) {
            return $this->error('雇主不能编辑（Employer Disabled Edit）', 'user/user-designer');
        }
        if($user) {
            unset($rule['param']['username']);
            $rule['param']['password_digest'][1]['required'] = false;
        }
        return $this->render('designer-detail', ['data' => $user, 'relate' => json_encode($rule)]);
    }
    /**
     * insert User
     * @method post
     * @return string html
     */
    public function actionUserInsert()
    {
        $rule = [
            'param' => [
                'username' => ['账号', ['username', 'required']],
                'password_digest' => ['密码', ['password', 'required']],
                'mobile' => ['手机号', ['mobile', 'required']],
                'nickname' => ['昵称', ['maxlength' => 16, 'required']],
            ],
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != SuccessCode) {
            return $this->error($checker['message'], 'user/designer-detail');
        }
        $user = new User();
        $user->loads($params);
        $user->registor = User::RegistorInner;
        $user->role = User::RoleDesigner;
        if ( ! $user->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($user->errors(), 'user/designer-detail');
        }
        if ($user->save()) {
            $user->initAccount();
            // 保存成功
            return $this->success('用户（'.$user->username.'）添加成功（Insert Success）', [
                ['title' => '前往用户列表页', 'url' => 'user/user-designer'],
                ['title' => '继续修改用户', 'url' => 'user/designer-detail?id='.$user->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('用户（'.$user->username.'）添加失败，请重试（System Fail）', 'user/designer-detail');
    }
    /**
     * update user information
     * @describe use get(id) to find User
     * @return string html
     */
    public function actionUserUpdate()
    {
        /* @var $user User */
        // id 为必填项，判断管理员存在状态
        $user = User::canEdit($this->request->get('id'));
        // 未得到，渲染错误页面
        if( ! $user) {
            return $this->error('无效的用户（Invalid User）', 'user/user-designer');
        }
        $params = $this->request->post();
        if(empty($params['password_digest'])) {
            unset($params['password_digest']);
        }
        $user->load(['User' => $params]);
        if ( ! $user->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($user->errors(), 'user/designer-detail?id='.$user->id);
        }
        if ($user->save()) {
            // 保存成功
            return $this->success('用户（'.$user->username.'）更新成功（Update Success）', [
                ['title' => '前往用户列表页', 'url' => 'user/user-designer'],
                ['title' => '继续修改用户', 'url' => 'user/designer-detail?id='.$user->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('用户（'.$user->username.'）更新失败，请重试（System Error）', 'user/designer-detail?id='.$user->id);
    }
    /**
     * delete User
     * @param id|ids array post request
     * @return string json
     */
    public function actionUserDelete()
    {
        if( ! (($ids = $this->request->post('id')) || ($ids = $this->request->post('ids')))) {
            return $this->json('Invalid.Param', '请求异常（Invalid Param）');
        }
        else if(User::trashAll(['id' => $ids])) {
            return $this->json(SuccessCode, '用户删除成功（Delete Success）');
        }
        return $this->json('System.Error', '用户删除失败（System Error）');
    }

    /**
     * user account
     * @param id array post request
     * @return string json
     */
    public function actionUserAccount()
    {
        if( ! $user = User::canEdit($this->request->get('id'))) {
            return $this->error('无效的用户（Invalid User）', 'user/user-designer');
        }
        return $this->render('user-account', ['user' => $user]);
    }

    /**
     * user resume
     * @param id array post request
     * @return string json
     */
    public function actionUserResume()
    {
        if( ! $user = User::canEdit($this->request->get('id'))) {
            return $this->error('无效的用户（Invalid User）', 'user/user-designer');
        }
        if( ! $this->request->IsPost) {
            return $this->render('user-resume', ['user' => $user, 'activationCode' => rand(100000, 999999)]);
        }
        $params = $this->request->post();
        // if(empty($params['password_digest'])) {
        //     unset($params['password_digest']);
        // }
        $params['salary'] = bcmul($params['salary'], 100);
        $checker = Checker::authentication(User::flyer('ensume'), $params);
        if($checker['code'] != SuccessCode) {
            return $this->error($checker['message'], 'user/user-resume?id='.$user->id);
        }
        $user->loads($params);
        $user->status = User::StatusActive;
        if($user->alipay_score >= User::BondAlipayScoreLimit) {
            $user->bond_status = User::BondStatusAlipay;
        }
        if ( ! $user->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($user->errors(), 'user/user-resume?id='.$user->id);
        }
        if ($user->save()) {
            $user->trashUploador(UserUpload::TypeDesign);
            // 保存成功
            return $this->success('用户（'.$user->username.'）简历审核成功（Verify Success）', [
                ['title' => '前往用户列表页', 'url' => 'user/user-designer'],
                ['title' => '继续审核简历', 'url' => 'user/user-resume?id='.$user->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('用户（'.$user->username.'）更新失败，请重试（System Error）', 'user/user-resume?id='.$user->id);
    }
  	
  	/**
     * user 芝麻信用等级验证
     * @param id array post request
     * @return string json
     */
    public function actionUserAlipayscore()
    {	
         if( ! $user = User::canEdit($this->request->get('id'))) {
            return $this->error('无效的用户（Invalid User）', 'user/user-designer');
        }
        if( ! $this->request->IsPost) {
            return $this->render('user-alipayscore', ['user' => $user, 'activationCode' => rand(100000, 999999)]);
        }
        $params = $this->request->post();
        $params['salary'] = bcmul($params['salary'], 100);
        $checker = Checker::authentication(User::flyer('alipayscore'), $params);
        if($checker['code'] != SuccessCode) {
            return $this->error($checker['message'], 'user/user-alipayscore?id='.$user->id);
        }
        $user->loads($params);
        $user->status = User::StausLevel;
        if ( ! $user->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($this->buildModelError($user), 'user/user-resume?id='.$user->id);
        }
        if ($user->save()) {
            // 保存成功
            return $this->success('用户（'.$user->username.'）简历审核成功（Verify Success）', [
                ['title' => '前往用户列表页', 'url' => 'user/user-designer'],
                ['title' => '继续审核简历', 'url' => 'user/user-alipayscore?id='.$user->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('用户（'.$user->username.'）更新失败，请重试（System Error）', 'user/user-resume?id='.$user->id);
	}
}